dofile (getScriptPath() .. "\\..\\processor\\processor.lua")
dofile (getScriptPath() .. "\\..\\processor\\log.lua")

dofile (getScriptPath() .. "\\..\\lib\\lib.lua")
dofile (getScriptPath() .. "\\..\\lib\\orders.lua")

script_name = string.gsub(string.gsub(debug.getinfo(1).short_src, "%.[^%.]*$", ""), "^.*[\\/]", "")


processor:AddInit(function()
	if not lib:isConnected() then return true end
	client_code = lib:GetUser()
	--if not client_code then return true end
	script_id = client_code .. "#" .. script_name
	--message("InitLog " .. lib.path.log .. script_id .. ".log")
	processor:InitLog(lib.path.log .. script_id .. ".log")
	processor:log("started")
end)
	
processor:AddInit(function()
	local ipos = lib:GetInstrumentPosition()
	processor:log("Instrument Positions", ipos)
	local spos = orders:GetPosition()
	processor:log("Stop Positions", spos)
	local n, srt
	--local overstop = {}
	for sec_code, sps in pairs(spos) do
		if ipos and ipos[sec_code] ~= 0 then
			n = math.abs(sps) - math.abs(int(ipos[sec_code]))
			processor:log(sec_code .. " " .. sps .. " " .. n)
			if n ~= 0 then
				--if not overstop[sec_code] or overstop[sec_code].n ~= n then
				--	overstop[sec_code] = {n = n, count = 3}
				--else
					--overstop[sec_code].count = overstop[sec_code].count - 1
					--if overstop[sec_code].count <= 0 then
						--overstop[sec_code] = nil
						processor:log(sec_code .. " set stops from " .. sps .. " to " .. int(ipos[sec_code]))
						if n < 0 then
							srt = "qty"
						else
							srt = "-qty"
						end
						for _, order in ipairs(orders:GetActiveStops(sec_code, srt)) do
							processor:log("SetStopLots " .. tostring(order.qty) .. " - " .. tostring(n), order)
							orders:SetStopLots(order, order.qty - n)
							n = n - order.qty
							if n <= 0 then
								break
							end
						end
					--end
				--end
			--elseif overstop[sec_code] then
			--	overstop[sec_code] = nil
			end
		end
	end

end)
	
processor:AddTimer(function()
	if not orders:InProcess() then
		processor:stop(0)
	end
end)


